// 位置服务工具类
const LocationService = {
  // 获取位置信息
  getLocation() {
    return new Promise((resolve, reject) => {
      // 检查小程序的位置权限
      wx.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.userLocation']) {
            // 如果未授权，向用户发起授权请求
            wx.authorize({
              scope: 'scope.userLocation',
              success: () => {
                this.getCurrentLocation(resolve, reject);
              },
              fail: (error) => {
                // 用户拒绝授权
                wx.showModal({
                  title: '需要位置权限',
                  content: '请允许使用位置权限，以便为您提供更好的服务',
                  confirmText: '去设置',
                  success: (res) => {
                    if (res.confirm) {
                      wx.openSetting({
                        success: (settingRes) => {
                          if (settingRes.authSetting['scope.userLocation']) {
                            this.getCurrentLocation(resolve, reject);
                          } else {
                            reject(new Error('用户未授权位置权限'));
                          }
                        }
                      });
                    } else {
                      reject(new Error('用户拒绝授权位置权限'));
                    }
                  }
                });
              }
            });
          } else {
            // 已有权限，直接获取位置
            this.getCurrentLocation(resolve, reject);
          }
        },
        fail: (error) => {
          reject(error);
        }
      });
    });
  },

  // 获取当前位置
  getCurrentLocation(resolve, reject) {
    wx.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
      highAccuracyExpireTime: 5000,
      success: (res) => {
        if (res.accuracy > 100) {
          setTimeout(() => {
            this.getCurrentLocation(resolve, reject);
          }, 1000);
          return;
        }
        resolve({
          latitude: res.latitude,
          longitude: res.longitude,
          accuracy: res.accuracy,
          speed: res.speed,
          altitude: res.altitude,
          verticalAccuracy: res.verticalAccuracy,
          horizontalAccuracy: res.horizontalAccuracy
        });
      },
      fail: (error) => {
        let errorMsg = '获取位置失败';
        if (error.errMsg.includes('auth deny')) {
          errorMsg = '位置权限被拒绝，请在设置中允许使用位置权限';
        } else if (error.errMsg.includes('system permission denied')) {
          errorMsg = '系统定位功能未开启，请检查系统设置';
        } else if (error.errMsg.includes('timeout')) {
          errorMsg = '定位超时，请检查GPS信号';
        }
        wx.showToast({
          title: errorMsg,
          icon: 'none',
          duration: 2000
        });
        reject(new Error(errorMsg));
      }
    });
  }
};

export default LocationService; 